import React, {createContext, useState, useContext, ReactNode} from 'react';
import {User, AuthContextType, AuthResult} from '../types/Auth';
import {loginUser, registerUser} from '../services/authService';

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider: React.FC<AuthProviderProps> = ({children}) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState<boolean>(false);

  const login = async (email: string, password: string): Promise<AuthResult> => {
    setLoading(true);
    try {
      const userData = await loginUser(email, password);
      setUser(userData);
      return {success: true};
    } catch (error) {
      return {
        success: false, 
        error: error instanceof Error ? error.message : '登录失败'
      };
    } finally {
      setLoading(false);
    }
  };

  const register = async (
    name: string, 
    email: string, 
    password: string
  ): Promise<AuthResult> => {
    setLoading(true);
    try {
      const userData = await registerUser(name, email, password);
      setUser(userData);
      return {success: true};
    } catch (error) {
      return {
        success: false, 
        error: error instanceof Error ? error.message : '注册失败'
      };
    } finally {
      setLoading(false);
    }
  };

  const logout = (): void => {
    setUser(null);
  };

  const value: AuthContextType = {
    user,
    login,
    register,
    logout,
    loading,
    isAuthenticated: !!user,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};